<template>
  <div class="my-articles-page">
    <van-nav-bar
      title="我的创作"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="articles-tabs">
      <van-tabs v-model:active="activeTab" animated swipeable>
        <van-tab title="已发布">
          <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list
              v-model:loading="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
            >
              <div class="article-list" v-if="publishedArticles.length > 0">
                <div 
                  v-for="(article, index) in publishedArticles" 
                  :key="article.id" 
                  class="article-item"
                  @click="viewArticle(article.id)"
                >
                  <div class="article-content">
                    <div class="article-title">{{ article.title }}</div>
                    <div class="article-info">
                      <span class="info-item">
                        <van-icon name="eye-o" />
                        <span>{{ article.views }}</span>
                      </span>
                      <span class="info-item">
                        <van-icon name="like-o" />
                        <span>{{ article.likes }}</span>
                      </span>
                      <span class="info-item">
                        <van-icon name="comment-o" />
                        <span>{{ article.comments }}</span>
                      </span>
                      <span class="article-time">{{ formatDate(article.createTime) }}</span>
                    </div>
                  </div>
                  <div class="article-actions">
                    <van-button size="small" plain type="primary" @click.stop="editArticle(article.id)">编辑</van-button>
                    <van-button size="small" plain type="danger" @click.stop="deleteArticle(article.id)">删除</van-button>
                  </div>
                </div>
              </div>
              <van-empty v-else description="暂无已发布的文章" />
            </van-list>
          </van-pull-refresh>
        </van-tab>
        
        <van-tab title="草稿">
          <div class="article-list" v-if="draftArticles.length > 0">
            <div 
              v-for="(article, index) in draftArticles" 
              :key="article.id" 
              class="article-item"
              @click="editArticle(article.id)"
            >
              <div class="article-content">
                <div class="article-title">{{ article.title || '无标题草稿' }}</div>
                <div class="article-info">
                  <span class="article-time">{{ formatDate(article.updateTime) }}</span>
                </div>
              </div>
              <div class="article-actions">
                <van-button size="small" plain type="primary" @click.stop="editArticle(article.id)">继续编辑</van-button>
                <van-button size="small" plain type="danger" @click.stop="deleteArticle(article.id, true)">删除</van-button>
              </div>
            </div>
          </div>
          <van-empty v-else description="暂无草稿" />
        </van-tab>
      </van-tabs>
    </div>
    
    <div class="floating-button" @click="createArticle">
      <van-icon name="plus" size="20" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'

const router = useRouter()
const activeTab = ref(0)
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const publishedArticles = ref([])
const draftArticles = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 下拉刷新
const onRefresh = () => {
  currentPage.value = 1
  finished.value = false
  loadArticles(true)
}

// 加载更多
const onLoad = () => {
  loadArticles()
}

// 加载文章列表
const loadArticles = async (isRefresh = false) => {
  if (activeTab.value === 0) {
    // 加载已发布文章
    await loadPublishedArticles(isRefresh)
  } else {
    // 加载草稿
    await loadDraftArticles()
  }
}

// 加载已发布文章
const loadPublishedArticles = async (isRefresh = false) => {
  try {
    // 模拟加载数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const mockData = Array(5).fill(0).map((_, index) => ({
      id: `pub-${currentPage.value}-${index}`,
      title: `已发布文章标题 ${currentPage.value}-${index}`,
      views: Math.floor(Math.random() * 1000),
      likes: Math.floor(Math.random() * 200),
      comments: Math.floor(Math.random() * 50),
      createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString()
    }))
    
    if (isRefresh) {
      publishedArticles.value = mockData
    } else {
      publishedArticles.value = [...publishedArticles.value, ...mockData]
    }
    
    currentPage.value++
    finished.value = currentPage.value > 3
  } catch (error) {
    console.error('加载已发布文章失败:', error)
    showToast('加载失败，请重试')
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 加载草稿
const loadDraftArticles = async () => {
  try {
    // 模拟加载数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    draftArticles.value = Array(3).fill(0).map((_, index) => ({
      id: `draft-${index}`,
      title: index % 2 === 0 ? `草稿标题 ${index}` : '',
      updateTime: new Date(Date.now() - Math.floor(Math.random() * 7) * 24 * 60 * 60 * 1000).toISOString()
    }))
  } catch (error) {
    console.error('加载草稿失败:', error)
    showToast('加载失败，请重试')
  }
}

// 查看文章
const viewArticle = (id) => {
  router.push(`/blog/${id}`)
}

// 编辑文章
const editArticle = (id) => {
  router.push(`/article/edit/${id}`)
}

// 创建新文章
const createArticle = () => {
  router.push('/article/create')
}

// 删除文章
const deleteArticle = (id, isDraft = false) => {
  showDialog({
    title: '确认删除',
    message: `确定要删除${isDraft ? '这篇草稿' : '这篇文章'}吗？`,
    showCancelButton: true
  }).then(() => {
    showToast('删除成功')
    
    if (isDraft) {
      draftArticles.value = draftArticles.value.filter(item => item.id !== id)
    } else {
      publishedArticles.value = publishedArticles.value.filter(item => item.id !== id)
    }
  }).catch(() => {
    // 取消操作
  })
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

onMounted(() => {
  loadArticles()
})
</script>

<style lang="scss" scoped>
.my-articles-page {
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: calc(var(--tabbar-height) + 20px);
  
  .articles-tabs {
    --van-tabs-line-height: 44px;
    
    .article-list {
      .article-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 12px;
        padding: 12px;
        background-color: var(--background-color-light);
        border-radius: 8px;
        
        .article-content {
          flex: 1;
          margin-right: 12px;
          
          .article-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 8px;
            line-height: 1.4;
            color: var(--text-color);
          }
          
          .article-info {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            font-size: 12px;
            color: var(--text-color-tertiary);
            
            .info-item {
              display: flex;
              align-items: center;
              margin-right: 12px;
              
              .van-icon {
                margin-right: 2px;
              }
            }
            
            .article-time {
              margin-left: auto;
            }
          }
        }
        
        .article-actions {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }
      }
    }
  }
  
  .floating-button {
    position: fixed;
    right: 20px;
    bottom: calc(var(--tabbar-height) + 20px);
    width: 48px;
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;
    background-color: var(--primary-color);
    color: #fff;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    z-index: 10;
  }
}
</style> 